/**
 * @description user service
 * **/


const { User } =  require('../db/model/index')
const { formateUser } = require('./_format')
const { enCrypto } = require('../utils/cryp')
/**
 *
 * @method 查询用户信息
 * @param {string} userName
 * @param {string} password
 */
async function getUserInfo (userName,password) {
  let whereopt = {
    userName
  }

  if (password) {
    whereopt = {...whereopt, password: password}
  }

  const result = await User.findOne({
    attributes: ['id', 'userName', 'nickName', 'picture','city', 'gender'],
    where: whereopt
  })

  if (result == null) {
    return result
  }

  // 数据格式化
  const data = formateUser(result.dataValues)
  return data

}

/**
 *
 * @param {string} userName
 * @param {string} password
 * @param {number} gender
 * @param {string} nickname
 */
async function createUser({ userName, password, gender = 3, nickName}) {
  const result =  User.create({
    userName,
    password: enCrypto(password),
    gender,
    nickName: nickName ? nickName : userName
  })
  return result.dataValues
}

/**
 *
 *
 * @param {string} userName
 */
async function deleteUser(userName) {
  const result = await User.destroy({
    where: {
      userName
    }
  })
  return result > 0
}

module.exports = {
  getUserInfo: getUserInfo,
  createUser,
  deleteUser
}